import utils from "../utils/index.js"
import {BaseUrl} from "@/utils/staticResource";

uni.$u.http.setConfig((config) => {
	/* config 为默认全局配置*/
	config.baseURL = BaseUrl; /* 根域名 */

	return config
})

// 请求拦截，使请求携带token
uni.$u.http.interceptors.request.use((config) => {
	const token = uni.getStorageSync("token");
	config.header.Authorization = "Bearer " + token;
	config.header.Accept = "application/json";
	return config;
})

//响应拦截
uni.$u.http.interceptors.response.use((response) => {
	if (response.data.code == 401) { // 服务端返回的状态码不等于200，则reject()
		// 清楚用户信息
		uni.removeStorageSync("userInfo")
		uni.removeStorageSync("token")
		uni.removeStorageSync("showLogin")
		uni.showToast({
			title: '请先登陆',
			duration: 2000,
			position: 'center',
			icon: 'none'
		})
		setTimeout(() => {
			uni.setStorageSync('isNeedLogin', true);
			uni.switchTab({
				url:'/pages/home/index',
			})
		},1000)
		return response.data
	}

	if (response.data.code !== 200) { // 服务端返回的状态码不等于200，则reject()
		uni.showToast({
			title: response.data.msg,
			duration: 2000,
			position: 'center',
			icon: 'none'
		})
	}
	return response.data;
}, (response) => {
	return response
})
export const request = uni.$u.http
